﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Windows.Media;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;

namespace DoubleH.Utility
{
   public class ImageUtility
    {
        public string ImageToString(string imgFile)
        {
            if (!File.Exists(imgFile))
                return string.Empty;

            Stream s = File.Open(imgFile, FileMode.Open);
            int leng = 0;
            if (s.Length < Int32.MaxValue)
                leng = (int)s.Length;
            byte[] by = new byte[leng];
            s.Read(by, 0, leng);//把图片读到字节数组中
            s.Close();

            return  Convert.ToBase64String(by);//把字节数组转换成字符串
        }

        public Image StringToImage(string text)
        {
            byte[] buf = Convert.FromBase64String(text);//把字符串读到字节数组中
            MemoryStream ms = new MemoryStream(buf);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            ms.Close();
            ms.Dispose();
            return img;
        }

        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))
                throw new System.ComponentModel.Win32Exception();

            return wpfBitmap;
        }
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
    }
}
